package com.pingan.pastry.service.impl;

import com.pingan.pastry.dao.MenuDAO;
import com.pingan.pastry.entity.Menu;
import com.pingan.pastry.entity.MenuDto;
import com.pingan.pastry.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuDAO menuDAO;

    @Override
    public List<MenuDto> listMenu(Integer userId) {
        return formatMenuDto(menuDAO.selectMenu(userId));
    }

    private List<MenuDto> formatMenuDto(List<Menu> menus) {
        List<MenuDto> menuDtos = new ArrayList<>();
        if (menus != null && menus.size() > 0) {
            for (Menu menu : menus) {
                if (menu.getLevel() == 1) {
                    MenuDto menuDto = new MenuDto();
                    menuDto.setName(menu.getName());
                    menuDto.setController("#");
                    String oneLevelId = menu.getId();
                    List<MenuDto> menuDtoTwoList = new ArrayList<>();
                    for (int i = 0; i < menus.size(); i++) {
                        Menu menuTwo = menus.get(i);
                        if (menuTwo.getParentId().equals(oneLevelId)) {
                            MenuDto childMenu = new MenuDto(menuTwo.getName(), menuTwo.getViewUrl(), null);
                            menuDtoTwoList.add(childMenu);
                            menuDto.setChild(menuDtoTwoList);
                        }
                    }
                    menuDtos.add(menuDto);
                }
            }
        }
        return menuDtos;
    }
}
